package org.changs.s3.common.analytics;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;

import com.google.android.gms.analytics.GoogleAnalytics;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;

import timber.log.Timber;

/**
 * Created by yincs on 2017/9/22.
 */

public class AnalyticsTracker extends FragmentManager.FragmentLifecycleCallbacks implements Application.ActivityLifecycleCallbacks {

    private final Tracker mTracker;

    public AnalyticsTracker(Context context, int configResId) {
        GoogleAnalytics analytics = GoogleAnalytics.getInstance(context);
        // To enable debug logging use: adb shell setprop log.tag.GAv4 DEBUG
        mTracker = analytics.newTracker(configResId);
    }

    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {

    }

    @Override
    public void onActivityStarted(Activity activity) {

    }

    @Override
    public void onActivityResumed(Activity activity) {
        CharSequence title = activity.getTitle();
        String resultTitle;
        if (title == null) {
            resultTitle = "车载项目测试界面:" + activity.getClass().getName();
        } else {
            resultTitle = title.toString();
        }
        screenView(resultTitle);
    }

    @Override
    public void onActivityPaused(Activity activity) {

    }

    @Override
    public void onActivityStopped(Activity activity) {

    }

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

    }

    @Override
    public void onActivityDestroyed(Activity activity) {

    }

    @Override
    public void onFragmentResumed(FragmentManager fm, Fragment f) {
        super.onFragmentResumed(fm, f);
        String resultTitle = "车载项目测试界面:" + f.getClass().getName();
        screenView(resultTitle);
    }

    private void screenView(String title) {
        Timber.d("title = " + title);
        mTracker.setScreenName(title);
        mTracker.send(new HitBuilders.ScreenViewBuilder().build());
    }
}
